package com.narbeshuber.tablet.lasalara.http;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.ByteArrayBuffer;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

import com.narbeshuber.tablet.lasalara.LasaLaraActivity;
import com.narbeshuber.tablet.lasalara.R;
import com.narbeshuber.tablet.lasalara.fragment.BookFragment;
import com.narbeshuber.tablet.lasalara.fragment.InfoFragment;
import com.narbeshuber.tablet.lasalara.fragment.InfoFragment.LayoutType;
import com.narbeshuber.tablet.lasalara.fragment.LoginFragment;
import com.narbeshuber.tablet.lasalara.fragment.LoginFragment.ErrorField;
import com.narbeshuber.tablet.lasalara.listadapters.BookAdapter;
import com.narbeshuber.tablet.lasalara.model.Book;

public class LoginTask extends AsyncTask<String, Object, String> {

	LasaLaraActivity lasalaraActivity;
	ProgressDialog dialog;
	public LoginTask(LasaLaraActivity lasalaraActivity){
		this.lasalaraActivity = lasalaraActivity;
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		dialog = ProgressDialog.show(lasalaraActivity, "", "Logging in...", true);
	}
	
	@Override
	protected String doInBackground(String... arg0) {
		
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost("http://1.narbeshuber.appspot.com/signin");
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
		String email = arg0[0].toLowerCase();
		String password = new String();
		nameValuePairs.add(new BasicNameValuePair("em", email));
		if (arg0[1].length() > 0)
			password = arg0[1].toLowerCase();
			nameValuePairs.add(new BasicNameValuePair("pw", password));
		try {
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			InputStream is = response.getEntity().getContent();
			BufferedInputStream bis = new BufferedInputStream(is, 700);				 				
			ByteArrayBuffer baf = new ByteArrayBuffer(20);
			int current = 0;
			while ((current = bis.read()) != -1) {
					baf.append((byte) current);
				}		
			final String retval = new String(baf.toByteArray());
			System.out.println(retval);
			return retval;			
		} catch (Exception e) {
			Log.e("Exception: ", e.getMessage());
		}
		return "";
	}

	 protected void onPostExecute(String result) {
		dialog.dismiss();
		try {
			JSONObject o = new JSONObject(result);
			if(o.has("err")){
				if(o.getString("err").equals("0")){
					//TextView errorMessage = (TextView) lasalaraActivity.findViewById(R.id.error_field);
					//errorMessage.setText("Invalid email or password.");
					LoginFragment.setErrorText("Invalid email or password", ErrorField.LOGIN_EMAIL);
					LoginFragment.setErrorText("Invalid email or password", ErrorField.LOGIN_PASSWORD);
				}
			}else{
				lasalaraActivity.getDbHelper().createDatabase();
				List<Book> books = new ArrayList<Book>();
				lasalaraActivity.getPrefsHelper().saveUserKey(o.getString("uk"));
				for (int i = 0; i < o.getJSONArray("books").length(); i++) {
					JSONObject jsonBook = o.getJSONArray("books").getJSONObject(i);	
					Book book = new Book();
					book.setKey(jsonBook.getString("bk"));
					book.setAuthorName(jsonBook.getString("name"));
					book.setAuthorEmail(jsonBook.getString("email"));
					book.setTitle(jsonBook.getString("title"));
					book.setDr(jsonBook.getString("dr"));
					book.setInstitution(jsonBook.getString("institution"));
					lasalaraActivity.getDbHelper().insertBook(book);
					books = lasalaraActivity.getDbHelper().getAllBooks();
				}
		        FragmentManager fragmentManager = lasalaraActivity.getFragmentManager();
				FragmentTransaction fragmentTransaction = fragmentManager
						.beginTransaction();
				BookFragment.getInstance().setListAdapter(new BookAdapter(lasalaraActivity, books));
				fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
				fragmentTransaction.replace(R.id.right, new InfoFragment(LayoutType.DEFAULT));
				fragmentTransaction.replace(R.id.left, BookFragment.getInstance());
				fragmentTransaction.commit();
			}
		} catch (JSONException e) {
			Log.e("Exception: ", e.getMessage());
		}
     }
}
